package com.banmao.mall.realm;

import com.banmao.mall.model.pojo.Admin;
import com.banmao.mall.model.vo.client.login.Client;
import com.banmao.mall.model.vo.client.login.UserInfoVO;
import com.banmao.mall.service.admin.AdminService;
import com.banmao.mall.service.client.ClientService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 *  管理员Realm
 */
@Component("clientRealm")
public class ClientRealm extends AuthorizingRealm {

    @Autowired
    @Lazy // 防止Spring事务注解失效
    ClientService clientService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;

        // 调用Service层 连接数据库
        Client userLogin = clientService.login(userToken.getUsername());

        if(userLogin == null) {
            // 没有这个用户
            return null;
        }


        // 获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("userId", userLogin.getId());

        // 从数据库中取该用户的password
        String password = userLogin.getPassword();

        // 加盐
        String salt = Integer.toString(userLogin.getId());

        // 创建SimpleAuthenticationInfo
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo("", password, this.getName());

        // 返回 return的过程完成password的验证
        return simpleAuthenticationInfo;
    }
}
